#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
description: please input using description
author: justbk
date: 2023/8/16
modify_records:
    - 2023/8/16 justbk create this file
"""
import os, sys
import sqlite3
from orm import *

class Sqlite3Operator(DbOperator):
    def __init__(self, db_name='test.db'):
        self.db_name = db_name
        self._conn = None
        self._cursor = None

    @property
    def conn(self):
        if self._conn is None:
            self._conn = sqlite3.connect(self.db_name)
        return self._conn

    @property
    def cursor(self):
        if self._cursor is None:
            self._cursor = self.conn.cursor()
        return self._cursor

    def execute(self, sql, *args):
        self.cursor.execute(sql, *args)
        self.conn.commit()

    def query(self, sql, *args):
        cur = self.cursor.execute(sql, *args)
        return cur.fetchall()

    def batch_insert(self, objs):
        if objs is None or len(objs) == 0:
            return
        sql = objs[0].get_insert_sql()
        datas = list(map(lambda obj: obj.to_sql_data(), objs))
        number = self.cursor.executemany(sql, datas)
        self.conn.commit()
        return number

class LsofModel(Model):
    TID = StringField("tid")
    TNAME = StringField("tname")
    FD = StringField("fd")
    FD_TYPE = StringField("fd_type")
    DEVICE = StringField("device")
    SIZE = StringField("size")
    NODE = StringField("node")
    NAME = StringField("name")

    PNAME = None
    PID = None
    USER = None

    @classmethod
    def parse(cls, str):
        values = str.strip().split()
        print(len(values), values)
        i = 0
        kwargs = {}
        while values[i] != cls.USER:
            i += 1
        if i == 2: # no tid and tname provides
            kwargs["tid"] = "0"
            kwargs["tname"] = "0"
        else:
            kwargs["tid"] = values[2]
            kwargs["tname"] = values[3]

        kwargs["fd"] = values[i + 1]
        kwargs["fd_type"] = values[i + 2]
        kwargs["device"] = (values[i + 3])
        if (len(values) - i) == 6:
            kwargs["size"] = "0"
            kwargs["node"] = values[i + 4]
            kwargs["name"] = values[i + 5]
        else:
            kwargs["size"] = values[i + 4]
            kwargs["node"] = values[i + 5]
            kwargs["name"] = values[i + 6]
        return LsofModel(**kwargs)


    @classmethod
    def init(cls, pname, pid, user):
        cls.PNAME = pname
        cls.PID = pid
        cls.USER = user

    def __str__(self):
        return self.tname + "-" + self.tid + "[" + self.fd_type + "]" +"[" + self.name + "]"
def test1():
    str1 = "gaussdb   3116565                          omm  cwd       DIR              253,2       4096     393217 /datafs/ogdata"
    struct = LsofModel.parse(str1)
    print(struct)
    str2 = "gaussdb   3116565 2550972 worker           omm 1156u     IPv4          100431170        0t0        TCP ogdb:quake->21.47.45.4:50560 (ESTABLISHED)"
    struct = LsofModel.parse(str2)
    print(struct)
    str3="gaussdb   3116565                          omm  DEL       REG                0,5                 32768 /SYSV018cba81"
    struct = LsofModel.parse(str3)
    print(struct)

def test():
    file_path = r'E:\社区支撑\兴业银行\lsof1101'
    file_name='ogdb_file.txt'
    file=os.path.join(file_path, file_name)
    print(os.path.exists(file))
    with open(file, "rt") as f:
        lines = f.readlines()
    results = []
    for l in lines:
        lm = LsofModel.parse(l)
        results.append(lm)
    print("********************total results=%d" % (len(results)))
    db = get_db()
    tmp = LsofModel()
    tmp.drop(db)
    tmp.create(db)
    db.batch_insert(results)
    results = tmp.query(db)
    print("********toatl query len:%s" %(len(results)))

def test2():
    str3 = "gaussdb   3116565                          omm  DEL       REG                0,5                 32768 /SYSV018cba81"
    l_model = LsofModel.parse(str3)
    db = Sqlite3Operator()
    l_model.drop(db)
    l_model.create(db)
    l_model.save(db)
    results = l_model.query(db)
    print(len(results))
    results = l_model.query_condition(db, "where fd_type=?", ('REG',))
    print(len(results))
DB = Sqlite3Operator()
def get_db():
    global DB
    return DB
if __name__ == '__main__':
    LsofModel.init("gaussdb", "3116565", "omm")
    test()
    # test2()